package com.hjy.core.transport.socket.server;

import com.hjy.core.handler.RequestHandler;
import com.hjy.core.nacos.NacosServiceRegistry;
import com.hjy.core.provider.DefaultServiceProvider;
import com.hjy.core.provider.ServiceProvider;
import com.hjy.core.transport.AbstractRpcServer;
import com.hjy.core.transport.RpcServer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class SocketServer extends AbstractRpcServer {
    private final ExecutorService threadPool;

    private static final int CORE_POOL_SIZE = 5; // 线程池大小
    private static final int MAXIMUM_POOL_SIZE = 50; // 最大大小
    private static final int KEEP_ALIVE_TIME = 60; // 存活时间
    private static final int BLOCKING_QUEUE_CAPACITY = 100; // 阻塞队列容量
    private RequestHandler requestHandler = new RequestHandler();

    public SocketServer(String host, int port) {
        this.serviceProvider = new DefaultServiceProvider();
        this.serviceRegistry = new NacosServiceRegistry();
        this.port = port;
        this.host = host;
        BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<>(BLOCKING_QUEUE_CAPACITY);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, workingQueue, threadFactory);
        // 扫描服务
        scanServices();
    }

    @Override
    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器启动...");
            Socket socket;
            while ((socket = serverSocket.accept()) != null) {
                System.out.println("客户端连接！Ip为：" + socket.getInetAddress() + " 端口为: " + socket.getPort());
                threadPool.execute(new RequestHandlerThread(socket, requestHandler, serviceProvider));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
